// Function to generate a database backup
function wp_auto_db_backup() {
    global $wpdb;
    
    // Get site name and date for filename
    $site_name = sanitize_title(get_bloginfo('name'));
    $date = date('Y-m-d_H-i-s');
    $backup_file = $site_name . '_db_backup_' . $date . '.sql';

    // Get database credentials
    $db_name = DB_NAME;
    $db_user = DB_USER;
    $db_password = DB_PASSWORD;
    $db_host = DB_HOST;

    // Command to export database (works if mysqldump is available on the server)
    $backup_dir = wp_upload_dir()['basedir'] . '/db_backups';
    if (!file_exists($backup_dir)) {
        mkdir($backup_dir, 0755, true);
    }
    
    $backup_path = $backup_dir . '/' . $backup_file;
    $command = "mysqldump --user=$db_user --password=$db_password --host=$db_host $db_name > $backup_path";

    system($command, $output);

    if (file_exists($backup_path)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($backup_path) . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($backup_path));
        readfile($backup_path);
        unlink($backup_path); // Delete after download
        exit;
    } else {
        wp_die('Database backup failed. Ensure mysqldump is enabled.');
    }
}

// Add a custom URL to trigger the backup
add_action('admin_init', function () {
    if (isset($_GET['download_db_backup']) && current_user_can('manage_options')) {
        wp_auto_db_backup();
    }
});

// Add a button in the admin menu
add_action('admin_menu', function () {
    add_menu_page(
        'DB Backup',
        'DB Backup',
        'manage_options',
        'wp-db-backup',
        'wp_db_backup_page',
        'dashicons-database'
    );
});

// Admin page content
function wp_db_backup_page() {
    ?>
    <div class="wrap">
        <h1>Database Backup</h1>
        <p>Click the button below to download the latest database backup.</p>
        <a href="<?php echo admin_url('?download_db_backup=1'); ?>" class="button button-primary">Download Backup</a>
    </div>
    <?php
}
